package com.hyacinth.security;

import com.google.common.collect.Sets;
import com.hyacinth.constant.Symbol;
import com.hyacinth.util.XaUtils;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * Class description: 权限相关公用方法
 *
 * @Version: V1.0, 2016/7/12 15:55
 * @JDK Version: 1.8.0_40
 * @Author: Chenshili
 */
@Slf4j
public class SecurityUtils {

    /**
     * 获取当前请求对应的正则URI
     * @param srcUrl url@method
     * @param urls
     * @return
     */
    public static String getRegexUrl(String srcUrl, Set<String> urls) {
        Pattern compile;
        String targetUrl = null;
        if(XaUtils.isEmpty(urls)){
            return null;
        }
        boolean found = false;
        for(String regex : urls){
            if(StringUtils.isBlank(regex)){
                continue;
            }
            String [] tmpRegex;
            int methodPos = regex.indexOf("@");
            int baseUrlPos = regex.lastIndexOf("/");
            String baseUrl = regex.substring(0, baseUrlPos + 1);
            String method = regex.substring(methodPos);
            String urlRegex = regex.substring(baseUrlPos + 1, methodPos);
            if(urlRegex.indexOf('|') != -1){
                tmpRegex = urlRegex.split("\\|");
            }else{
                tmpRegex = new String[]{urlRegex};
            }
            for(String tmp : tmpRegex){
                compile = Pattern.compile(baseUrl + tmp + method);
                if(compile.matcher(srcUrl).matches()){
                    targetUrl = regex;
                    found = true;
                    break;
                }
            }
            if(found){
                break;
            }
        }
        return targetUrl;
    }

    /**
     * 正则匹配
     * @param regex
     * @param servletPath
     * @return true:匹配；false：不匹配
     */
    public static boolean isRegex(String regex, String servletPath){
        Pattern compile = Pattern.compile(regex);
        return compile.matcher(servletPath).matches();
    }
}
